package com.eorchis.module.user.ui.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.eorchis.core.page.commond.JSONObject;
import com.eorchis.core.ui.token.IToken;
import com.eorchis.module.ModelBeanUtils;
import com.eorchis.module.basedata.domain.BaseData;
import com.eorchis.module.basedata.service.cache.BaseDataCacheUtil;
import com.eorchis.module.classuser.dao.IClassUserDao;
import com.eorchis.module.classuser.domain.ClassUser;
import com.eorchis.module.classuser.domain.QueryClassUserBean;
import com.eorchis.module.classuser.service.IClassUserService;
import com.eorchis.module.department.domain.Department;
import com.eorchis.module.department.domain.DepartmentUser;
import com.eorchis.module.department.service.IDepartmentUserService;
import com.eorchis.module.user.domain.Months;
import com.eorchis.module.user.domain.User;
import com.eorchis.module.user.domain.UserInfoCondition;
import com.eorchis.module.user.domain.Years;
import com.eorchis.module.user.service.IUserInfoService;
import com.eorchis.module.user.service.IUserUpdateService;
import com.eorchis.module.user.ui.commond.UserInfoCommond;
import com.eorchis.module.user.ui.commond.UserInfoValidCommond;
import com.eorchis.utils.utils.PropertyUtil;

@Controller("userInfoController")
@RequestMapping({ "/module/user" })
@SuppressWarnings("deprecation")
public class UserInfoController {
	public static final String modulePath = "/module/user";

	@Autowired
	@Qualifier("com.eorchis.module.user.service.impl.UserInfoServiceImpl")
	private IUserInfoService iUserInfoService;
	

	@Resource(name = "com.eorchis.module.classuser.dao.impl.ClassUserDaoImpl")
	private IClassUserDao classUserDao;

	//数据字典缓存
	@Resource(name = "com.eorchis.module.basedata.service.cache.BaseDataCacheUtil")
	private BaseDataCacheUtil baseDataCacheUtil;
	
	@Autowired
	@Qualifier("com.eorchis.module.department.service.impl.DepartmentUserServiceImpl")
	private IDepartmentUserService departmentUserService;

	// 培训班用户关系接口
	@Resource(name = "com.eorchis.module.classuser.service.impl.ClassUserServiceImpl")
	private IClassUserService classUserService;

	// 班级计划报名接口
//	@Autowired
//	@Qualifier("com.eorchis.module.classplanapply.service.impl.ClassPlanApplyServiceImpl")
//	private IClassPlanApplyService classPlanApplyService;

	//修改记录接口
	@Autowired
	@Qualifier("com.eorchis.module.user.service.impl.UserUpdateServiceImpl")
	private IUserUpdateService userUpdateService;
	
	@Autowired
	private IToken token;

	@RequestMapping({ "/listUser" })
	public String listUser(Model model, UserInfoCommond userCommond) throws Exception {
		UserInfoCondition condition = new UserInfoCondition();
		BeanUtils.copyProperties(userCommond, condition);
		JSONObject result = this.iUserInfoService.doProcess(userCommond, condition);
		ModelBeanUtils.jsonObjectToModel(result, model);
		return "forward:/module/user/listUser.jsp";
	}

	@RequestMapping({ "/preAddUser" })
	public String preAddUser(Model model, HttpServletRequest request, UserInfoValidCommond userValidCommond) throws Exception {
		ModelBeanUtils.jsonObjectToModel(model, true, null, userValidCommond);
		return "forward:/module/user/addUser.jsp";
	}

	@RequestMapping({ "/saveToken" })
	public String preAddUser(HttpServletRequest request) throws Exception {
		String tokenStr = this.token.saveToken(request);
		return tokenStr;
	}

	@RequestMapping({ "/addUser" })
	public String addUser(Model model, HttpServletRequest request, UserInfoValidCommond userValidCommond) throws Exception {
		User user = null;

		if (this.token.isTokenValid(request, true)) {
			user = new User();

			BeanUtils.copyProperties(userValidCommond, user, new String[] { "sexCode", "folkCode", "paperTypeCode", "politicesCode", "degreeCode", "dutyLevelCode", "birthday", "administrativeLevel" });

			if (userValidCommond.getSexCode() != null) {
				BaseData bd = new BaseData();
				bd.setDataCode(userValidCommond.getSexCode());
				user.setSexCode(bd);
			}
			
			if (userValidCommond.getFolkCode() != null) {
				BaseData bd = new BaseData();
				bd.setDataCode(userValidCommond.getFolkCode());
				user.setFolkCode(bd);
			}
			
			if (userValidCommond.getAdministrativeLevel() != null) {
				BaseData bd = new BaseData();
				bd.setDataCode(userValidCommond.getAdministrativeLevel());
				user.setAdministrativeLevel(bd);
			}

			if ((userValidCommond.getBirthday() != null) && (!"".equals(userValidCommond.getBirthday()))) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				user.setBirthday(sdf.parse(userValidCommond.getBirthday()));
			}

			Department department = new Department();
			department.setDeptID(userValidCommond.getDepartmentId());
			user.setActiveState(User.IS_ACTIVE_Y);
			this.iUserInfoService.addUser(user);

			DepartmentUser departmentUser = new DepartmentUser();
			departmentUser.setUser(user);
			departmentUser.setDepartment(department);
			departmentUser.setActiveState(Integer.valueOf(1));
			departmentUser.setOrderNum(Integer.valueOf(1));
			this.departmentUserService.addDepartmentUser(departmentUser);

			ModelBeanUtils.jsonObjectToModel(model, true, "添加成功！", user);
		}

		return "forward:/module/userlistUser.do";
	}

	@RequestMapping({ "/preUpdateUser" })
	public String preUpdateUser(Model model, HttpServletRequest request, UserInfoValidCommond userValidCommond) throws Exception {
		UserInfoCondition userCondition = null;
		User user = null;
		ClassUser classUser=null;
		String classId=null;
		String userId=null;
		if((userValidCommond.getSearchClassID()!=null)&&(!"".equals(userValidCommond.getSearchClassID()))){
			classId=userValidCommond.getSearchClassID();
	 		if ((userValidCommond.getSearchUserId() != null) && (!"".equals(userValidCommond.getSearchUserId()))) {
	 			userId=userValidCommond.getSearchUserId();
	 			classUser=classUserService.getUser(classId,userId);
	 			userCondition=new UserInfoCondition();
	 			userCondition.setSearchUserId(userValidCommond.getSearchUserId());
				QueryClassUserBean us2=classUserDao.getUserbyUnified(userValidCommond.getSearchUserId());
	 			user = this.iUserInfoService.getUser(userCondition);
	//			BeanUtils.copyProperties(user, userValidCommond, new String[] { "sexCode", "folkCode", "paperTypeCode", "politicesCode", "degreeCode", "dutyLevelCode", "birthday", "administrativeLevel" });
				if (us2.getSexCode() != null)
					userValidCommond.setSexCode(us2.getSexCode());
				if (us2.getFolkCode() != null)
					userValidCommond.setFolkCode(us2.getFolkCode());
				if (us2.getRankCode()!= null)
					userValidCommond.setRank(us2.getRankCode());
				if (user.getAdministrativeLevel() != null)
					userValidCommond.setAdministrativeLevel(user.getAdministrativeLevel().getDataCode());
				if ((us2.getBirthday() != null) && (!"".equals(us2.getBirthday()))) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
					userValidCommond.setBirthday(sdf.format(us2.getBirthday()));
					userValidCommond.setBirthdayYear(userValidCommond.getBirthday().substring(0,4));
					userValidCommond.setBirthdayMouth(userValidCommond.getBirthday().substring(5,7));
				}
				userValidCommond.setUserName(us2.getUserName());
				userValidCommond.setDutyRemark(us2.getDutyRemark());
				if(!"无数据".equals(us2.getMobileTelephone())){
					userValidCommond.setMobileTelephone(us2.getMobileTelephone());
				}
				userValidCommond.setRemark(classUser.getRemark());
				/*Object o=null;
				Role currentRole = (Role) request.getSession().getAttribute(SessionConstant.CURRENT_ROLE);
				if (currentRole.getRoleCode().equals(DeptConstants.SUPER_BUSINESS_GJC))
					o = classUserDao.getUserLv1DeptNameByUserId(userValidCommond);
				else
					o = classUserDao.getUserDeptNameByUserId(userValidCommond);
				userValidCommond.setDeptName(o.toString());*/
	//			userValidCommond.setSearchDepID(searchDepID);
	//			userValidCommond.setDeptName(deptName);
				ModelBeanUtils.jsonObjectToModel(model, true, null, userValidCommond);
			}
		}

		return "/module/user/view";
	}

	@RequestMapping({"/yearMonth"})
	public String yearMonth(Model model,HttpServletRequest request){
		Date date=new Date();
		String year=new SimpleDateFormat("yyyy").format(date);
		ArrayList<Years> Y=new ArrayList<Years>();
		ArrayList<Months> M=new ArrayList<Months>();
		for(int i=0;i<=Integer.valueOf(year)-1950;i++){
			Y.add(new Years((1950+i)+""));
		}
		for(int i=1;i<=12;i++){
			M.add(new Months(i+""));
		}
		model.addAttribute("YEARS", Y);
		model.addAttribute("MONTHS", M);
		return "";
	}
	
	@RequestMapping({ "/updataUser" })
	public String updataUser(Model model, HttpServletRequest request, UserInfoValidCommond userValidCommond) throws Exception {
		User user = null;
		if (this.token.isTokenValid(request, true)) { 
			if (!PropertyUtil.objectNotEmpty(request.getParameter("searchClassID"))) {
				ModelBeanUtils.jsonObjectToModel(model, false, "查询不到此班级！", null);
				return "";
			}
			//保存最后一次修改报名学员日志
			userUpdateService.saveChangeinfoLog(userValidCommond);
			user = new User();
			/*ClassPlanApplyQueryCommond applyCommond=new ClassPlanApplyQueryCommond();
			//queryCommond.setSearchDepId("7449");
			com.eorchis.module.security.cas.domain.Department d=(com.eorchis.module.security.cas.domain.Department)request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
			applyCommond.setSearchDeptId(d.getDeptID());
			applyCommond.setSearchClassId(request.getParameter("searchClassID"));*/
			UserInfoCondition userCondition = new UserInfoCondition();
			userCondition.setSearchUserId(userValidCommond.getUserId());
			user = this.iUserInfoService.getUser(userCondition);
//			QueryClassUserBean us2=classUserDao.getUserbyUnified(user.getUserId());
			/*if (!user.getAdministrativeLevel().getDataCode().equals(userValidCommond.getAdministrativeLevel())) {
				String level = userValidCommond.getAdministrativeLevel();
				ClassPlanApplyValidCommond count = new ClassPlanApplyValidCommond();
				count = classPlanApplyService.findClassAsignCount(applyCommond);
				if (level.equals(ClassPlanApply.LEVEL_CITY)) {
					if (count.getAsignCityCount() <= count.getReportedCityCount()) {
						ModelBeanUtils.jsonObjectToModel(model, true, "此单位可报市级名额已满，请联系承办部委！", user);
						return "";
					}
				} else if (level.equals(ClassPlanApply.LEVEL_COUNTY)) {
					if (count.getAsignCountyCount() <= count.getReportedCountyCount()) {
						ModelBeanUtils.jsonObjectToModel(model, true, "此单位可报县级名额已满，请联系承办部委！", user);
						return "";
					}
				}
			}*/
			BeanUtils.copyProperties(userValidCommond, user, new String[] { "sexCode", "folkCode", "paperTypeCode", "politicesCode", "degreeCode", "dutyLevelCode", "birthday", "loginID", "administrativeLevel" });

			Map<String, BaseData> baseDataMap=baseDataCacheUtil.getBaseData();
			
			if (userValidCommond.getSexCode() != null) {
				BaseData bd = new BaseData();
				bd.setDataCode(userValidCommond.getSexCode());
				bd.setDataName(baseDataMap.get(bd.getDataCode()).getDataName());
				user.setSexCode(bd);
			}
			if ((userValidCommond.getBirthdayYear() != null) && (!"".equals(userValidCommond.getBirthdayYear()))&&(userValidCommond.getBirthdayMouth() != null) && (!"".equals(userValidCommond.getBirthdayMouth()))) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
				user.setBirthday(sdf.parse(userValidCommond.getBirthdayYear()+"-"+userValidCommond.getBirthdayMouth()));
			}
			if (userValidCommond.getActiveState() != null)
				user.setActiveState(userValidCommond.getActiveState());
			else if (userValidCommond.getActiveState() == null) {
				user.setActiveState(User.IS_ACTIVE_Y);
			}
			if (PropertyUtil.objectNotEmpty(userValidCommond.getFolkCode())) {
				BaseData bd = new BaseData();
				bd.setDataCode(userValidCommond.getFolkCode());
				bd.setDataName(baseDataMap.get(bd.getDataCode()).getDataName());
				user.setFolkCode(bd);
			}
			if (PropertyUtil.objectNotEmpty(userValidCommond.getAdministrativeLevel())) {
				BaseData bd = new BaseData();
				bd.setDataCode(userValidCommond.getAdministrativeLevel());
				user.setAdministrativeLevel(bd);
			}
			if (PropertyUtil.objectNotEmpty(userValidCommond.getRank())) {
				BaseData bd = new BaseData();
				bd.setDataCode(userValidCommond.getRank());
				bd.setDataName(baseDataMap.get(bd.getDataCode()).getDataName());
				user.setDutyLevelCode(bd);
			}
			user.setOperateTime(new Date());
			//this.iUserInfoService.updateUser(user);
//			Role currentRole = (Role)request.getSession().getAttribute(SessionConstant.CURRENT_ROLE);
//			String roleCode = currentRole.getCode();
//			Integer auditingState=ClassUser.NO_AUDITING;//单位管理员修改人员后是待审核
//			if(PropertyUtil.objectNotEmpty(roleCode)
//					&&!(RoleConstants.ROLE_CODE_DW_ADMIN.equals(roleCode))){
//				auditingState=ClassUser.IS_AUDITING_Y;//中组部和部委管理员修改人员后是审核通过
//			}
			Integer auditingState=ClassUser.NO_AUDITING;//修改人员后是待审核
//			if(PropertyUtil.objectNotEmpty(userValidCommond.getSignUpState())&&userValidCommond.getSignUpState().toString().equals("2")){
//				auditingState=ClassUser.IS_AUDITING_Y;
//			}else{
//				ClassUserQueryCommond classUserQueryCommond=new ClassUserQueryCommond();
//				classUserQueryCommond.setSearchUserID(userValidCommond.getUserId());
//				Object o=classUserDao.getClassUserByUserId(classUserQueryCommond);
//				if(PropertyUtil.objectNotEmpty(o)){
//					auditingState=Integer.valueOf(o.toString());
//				}
//			}
			classUserService.updateClassUserByUserId(user,auditingState,userValidCommond.getSearchClassID());
			
//			User cu=(User) request.getSession().getAttribute(SessionConstant.USER_INFO);
			//向统一用户平台更新用户
			try{
//				市管不更新，不存在不更新
				if(classUserDao.isShiguanOrJj(userValidCommond.getUserId())&&!user.getDutyLevelCode().getDataCode().equals("1380")&&!user.getDutyLevelCode().getDataCode().equals("1381")){
					//更新临时用户
					classUserDao.updateTempUser(user);
					//更新正式用户
					classUserDao.updateUser(user);
				}else{
					//局级同步手机号，职务，民族
					classUserDao.updateJJUserByUnified(user);
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				//记录审计日志
//				classUserDao.auditUserLogUpdate(us2,cu.getUserID(),IPUtil.getIP(request));
			}
			
			ModelBeanUtils.jsonObjectToModel(model, true, "修改成功！", user);
		}
		return "forward:/module/userlistUser.do";
	}

	@RequestMapping({ "/discardOrReuseUser" })
	public String discardOrReuseUser(Model model, HttpServletRequest request, UserInfoCommond userCommond) throws Exception {
		if ((userCommond.getSearchIsEnabled() != null) && (!"".equals(userCommond.getSearchIsEnabled())) && (userCommond.getSearchUserIds() != null) && (userCommond.getSearchUserIds().length > 0)) {
			UserInfoCondition userCondition = new UserInfoCondition();
			userCondition.setSearchUserIds(userCommond.getSearchUserIds());
			userCondition.setSearchIsEnabled(userCommond.getSearchIsEnabled());
			this.iUserInfoService.discardOrReuseUser(userCondition);
			ModelBeanUtils.jsonObjectToModel(model, true, "修改成功！", userCommond);
		} else {
			ModelBeanUtils.jsonObjectToModel(model, false, "操作数据为空", null);
		}
		return "forward:/module/userlistUser.do";
	}

	@RequestMapping({ "/checkIsRepeatUser" })
	public String checkIsRepeatUser(Model model, UserInfoValidCommond userValidCommond) throws Exception {
		if ((userValidCommond.getLoginID() != null) && (this.iUserInfoService.checkIsRepeatUser(userValidCommond.getLoginID(), userValidCommond.getUserId()))) {
			ModelBeanUtils.jsonObjectToModel(model, true, null, "true");
			return "";
		}
		ModelBeanUtils.jsonObjectToModel(model, false, "登陆名不能重复", null);

		return "";
	}
}